package com.vogue.meeting.common.security.granter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.vogue.meeting.common.security.model.Oauth2User;
import com.vogue.meeting.common.security.service.Oauth2UserDetailsService;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import java.util.Map;

/**
 * 账号密码获取token
 */
public class AccountPasswordTokenGranter extends AbstractCustomTokenGranter {

    protected Oauth2UserDetailsService userDetailsService;

    public AccountPasswordTokenGranter(Oauth2UserDetailsService userDetailsService, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, "password");
        this.userDetailsService = userDetailsService;

    }

    @Override
    protected Oauth2User getCustomUser(Map<String, String> parameters) {

        String account = parameters.get("account");
        String password = SecureUtil.md5(parameters.get("password"));

        if (StrUtil.isBlank(account)) {
            throw new UsernameNotFoundException("没有获取到您输入的账号");
        }

        Oauth2User oauth2User = userDetailsService.loadUserByUsername(account);

        if (oauth2User.getPassword().equals(password)){
            //TODO 1、根据Scope设置oauth2User可以访问的资源
            //TODO 2、根据oauth2User拥有的角色和系统权限设置可以访问的资源
            oauth2User.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_API"));
            return oauth2User;
        }else {
            throw new BadCredentialsException("秘密不正确");
        }

    }

}
